﻿using InDepth2Demo.Common;
using InDepth2Demo.Model;
using System;
using System.Collections.Generic;
using System.Linq;

namespace InDepth2Demo.Chapter1.C41
{
    /// <summary>
    /// 查询表达式
    /// </summary>
    internal class QueryExpression
    {
        // 使用查询表达式的前几步：筛选集合
        static void Call1()
        {
            List<Product> products = Product.GetSampleProducts();
            var filtered = from Product p in products
                           where p.Price > 10
                           select p;
            foreach (Product product in filtered)
            {
                Console.WriteLine(product);
            }
        }

        // 联接(joining)、筛选(filtering)、排序(ordering) 和 投影(projecting) (C# 3)
        static void Call2()
        {
            List<Product> products = Product.GetSampleProducts();
            List<Supplier> suppliers = Supplier.GetSampleSuppliers();
            var filtered = from p in products
                           join s in suppliers
                             on p.SupplierID equals s.SupplierID
                           where p.Price > 10
                           orderby s.Name, p.Name
                           select new { SupplierName = s.Name, ProductName = p.Name };
            foreach (var product in filtered)
            {
                Console.WriteLine(product);
            }
        }

        // 对SQL数据库应用查询表达式 (C#3)
        public static void Call3()
        {
            using (LinqDemoDataContext db = new LinqDemoDataContext())
            {
                var filtered = from em in db.Employees
                               join emAdd in db.EmployeesAddInfos
                                 on em.EM_ID equals emAdd.EM_ID
                               where em.Name.StartsWith("白")
                               select new
                               {
                                   EmpName = em.Name,
                                   City = emAdd.HRMS_UserField_34
                               };
                foreach (var emp in filtered)
                {
                    Console.WriteLine($"{emp.EmpName} - {emp.City}");
                }
            }
        }

        // 以后会知道，当模式 (schema) 和实体 (entity) 知道了供货商和产品之间的关系后，可以使用一种更面向关系 (relation-oriented) 的方式来进行联接
    }
}
